﻿using System;
using System.Collections.Generic;
using System.IO;
using CSJ2K.Util.IO;

namespace CSJ2K.Jpc.Segments
{
    /// <summary>Packet length, main header (PLM)</summary>
    /// <comment>
    /// Function: A list of packet lengths in the tile-parts for every tile-part in order. 
    /// Usage: Main header. There may be multiple PLM marker segments. Both the PLM and PLT 
    ///      marker segments are optional and can be used together or separately. 
    /// Length: Variable depending on the number of tile-parts in the image and the number of 
    ///      packets in each tile-part.
    /// </comment>
    public class PLM : Segment
    {
        /// <summary>Index of this marker segment relative to all other PLM marker segments present in the current header.</summary>
        public byte Z;

        public class TilePartInfo
        {
            /// <summary>Number of bytes of Iplm information for the ith tile-part in the order found in the codestream.</summary>
            public byte N { get { return (byte)I.Length; } }

            /// <summary>Length of the jth packet in the ith tile-part.</summary>
            public byte[] I;
        }
        public TilePartInfo[] TilePart;

        public PLM(Stream source)
            : this(source, (Markers)StreamUtil.ReadBUInt16(source)) { }
        public PLM(Stream source, Markers marker)
            : base(source, marker, true)
        {
            if (marker != Markers.PLM) throw (new ApplicationException("Attempting to create segment of the wrong type."));

            // TODO: Deserialize MarkerSegment
            byte[] buffer = StreamUtil.ReadBytes(source, Length - 2);
        }
    }
}
